<!--
 * @Description: 字典管理
 * @FilePath: \hk-iot\src\views\system\dic\index.vue
 * @Date: 2023-07-25 09:07:26
 * @LastEditTime: 2023-11-29 14:49:19
-->
<template>
  <div class="my-container layout-padding">
    <div class="group-left card-bg">
      <div class="list-header">
        <span class="title">字典列表</span>
        <div class="btn1 ml10" @click="onOpenDicTypeDialog">
          <el-icon> <ele-FolderAdd /> </el-icon><span class="ml6">添加项目</span>
        </div>
        <!-- <el-button size="small" type="success" class="ml10" @click="onOpenDicTypeDialog">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					添加项目
				</el-button> -->
      </div>

      <!-- <div style="padding: 10px;">
        <el-input v-model="state.dicTypeKeyWord" placeholder="输入字典名称(模糊搜索)" clearable >
          <template #append>
            <el-button size="small" type="success" @click="getDicTypeListByName()">
              <el-icon>
                <ele-Search/>
              </el-icon>
              搜索
            </el-button>
          </template>
        </el-input>
      </div> -->

      <el-scrollbar style="height: calc(100% - 50px)">
        <div class="list-box">
          <ul v-if="state.dicTypeList.length">
            <li class="item" :class="{ isActive: item.id == state.selectedDicTypeItem.id }" title="右键操作此项"
              v-for="item in state.dicTypeList" :key="item.id" @click="selectDicTypeItem(item)"
              @contextmenu.prevent="onContextmenu(item, $event)">
              {{ item.name }}
            </li>
          </ul>
          <el-empty v-else description="暂无数据" />
        </div>
      </el-scrollbar>
    </div>

    <div class="group-right card-bg">
      <div class="box-details energy-table">
        <div class="box-title">
          <div class="title">{{ state.tableData.dicDetailsList.length ? state.selectedDicTypeItem.name : '暂无' }}字典项</div>
          <div class="box-search">
            <div class="btn1 ml10" @click="onOpenDicDetailsDialog(null)">
              <el-icon> <ele-Plus /> </el-icon><span class="ml6">添加字典子项</span>
            </div>
          </div>
        </div>
        <el-table :data="state.tableData.dicDetailsList" style="width: 100%" row-key="id"
          :cell-style="{ textAlign: 'center' }" :row-style="{ background: '#0F2C6A' }"
          :header-cell-style="{ background: '#1E4897', color: '#499AFD', textAlign: 'center' }" size="default">
          <el-table-column prop="name" label="名称" width="220" sortable fixed />
          <el-table-column prop="code" label="键值" width="220" sortable />
          <el-table-column prop="seq" label="排序" width="220" sortable />
          <el-table-column prop="remark" label="备注" width="220" sortable />
          <el-table-column prop="createTime" label="创建时间" width="220" sortable />
          <el-table-column prop="updateTime" label="更新时间" width="220" sortable />
          <el-table-column fixed="right" label="操作" width="210">
            <template #default="scope">
              <el-button link type="success" size="small" @click="onOpenDicDetailsDialog(scope.row, true)">新增</el-button>
              <el-button link type="primary" size="small" @click="onOpenDicDetailsDialog(scope.row, false)">编辑</el-button>
              <el-popconfirm title="确定删除吗？" @confirm="onDelDicDetails(scope.row)">
                <template #reference>
                  <el-button link type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <AddDicTypeDialog ref="addDicTypeDialogRef" @on-param-submit="onDicTypeSubmit" />
    <AddDicTypeDetailsDialog ref="addDicTypeDetailsDialogRef" @on-param-submit="onDicTypeDetailsSubmit" />
    <Contextmenu :dropdown="state.dropdown" :dropdownList="state.dropdownList" ref="contextmenuRef"
      @currentContextmenuClick="onCurrentContextmenuClick" />
  </div>
</template>

<script lang="ts" setup name="systemDic">
import { ElMessageBox, ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { reactive, onMounted, ref, computed, watch } from 'vue';
import { useDicApi } from '/@/api/system/dic';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { useThemeConfig } from '/@/stores/themeConfig';
import AddDicTypeDialog from '/@/views/system/dic/component/addDicTypeDialog.vue';
import AddDicTypeDetailsDialog from '/@/views/system/dic/component/addDicTypeDetailsDialog.vue';
import Contextmenu from '/@/components/contextMenu/index.vue'; // 右键菜单

const storesThemeConfig = useThemeConfig();
const storesTagsViewRoutes = useTagsViewRoutes();
const { themeConfig } = storeToRefs(storesThemeConfig);
const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);

const addDicTypeDialogRef = ref(); // 新增项目对话框
const addDicTypeDetailsDialogRef = ref(); // 新增字典子项对话框
const contextmenuRef = ref(); // 右键

const state = reactive<any>({
  // 左侧当前选中项
  selectedDicTypeItem: {},
  // 当前搜索字典类型的名称
  dicTypeKeyWord: '',
  // 字典类型的列表
  dicTypeList: [{ label: '项目', value: '1' }],

  // 右侧---表单
  tableData: {
    dicDetailsList: [], // 字典参数列表
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 20,
    },
  },
  maintenanceChildItemList: [],

  // 右键
  dropdown: { x: '', y: '' },
  dropdownList: [
    { contextMenuClickId: 0, txt: '删除', icon: 'ele-Delete' },
    { contextMenuClickId: 1, txt: '编辑', icon: 'ele-Edit' },
  ],
});

// 设置主内容的高度
const initTagViewHeight = computed(() => {
  let { isTagsview } = themeConfig.value;
  // 如果开启全屏
  if (isTagsViewCurrenFull.value) {
    return `0px`;
  } else {
    if (isTagsview) return `84px`;
    else return `80px`;
  }
});

// 大项-右键点击时：传 x,y 坐标值到子组件中（props）
const onContextmenu = (v: any, e: any) => {
  const { clientX, clientY } = e;
  state.dropdown.x = clientX;
  state.dropdown.y = clientY;
  contextmenuRef.value.openContextmenu(v);
};

// 当前项右键菜单点击
const onCurrentContextmenuClick = async (item: any) => {
  switch (item.contextMenuClickId) {
    case 0:
      // 删除
      deleteLeftItem(item);
      break;
    case 1:
      // 编辑
      editLeftItem(item);
      break;
  }
};

// 删除左侧项目
const deleteLeftItem = (item: any) => {
  ElMessageBox.confirm(`确认删除此项目, 是否继续?`, '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      useDicApi()
        .deleteDicType({ id: item.id })
        .then((data: any) => {
          getDicTypeListByName();
          ElMessage.success(data.msg || '删除成功');
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '操作取消',
      });
    });
};

// 编辑左侧项目
const editLeftItem = (item: any) => {
  addDicTypeDialogRef.value.openDialog(item);
};

// 监听高度改变，触发window中的resize事件
watch(initTagViewHeight, () => {
  let myEvent = new Event('resize');
  window.dispatchEvent(myEvent);
});

// 页面加载时
onMounted(() => {
  getDicTypeListByName();
});

// 通过字典名称查询所有字典
const getDicTypeListByName = async () => {
  //查询所有医院信息
  await useDicApi()
    .queryDicTypeList()
    .then((res: any) => {
      if (res.data.length) {
        state.dicTypeList = res.data;
        state.selectedDicTypeItem = res.data[0];
        selectDicTypeItem(state.selectedDicTypeItem);
      }
    });
};

// 添加大项
const onOpenDicTypeDialog = (row: any) => {
  console.log(row);
  addDicTypeDialogRef.value.openDialog();
};

// 添加单项
const onOpenDicDetailsDialog = (row = null, isRowAdd = false) => {
  // 如果是行内新增
  if (isRowAdd) {
    addDicTypeDetailsDialogRef.value.openDialogOnRow(state.selectedDicTypeItem, state.tableData.dicDetailsList, row);
  } else {
    addDicTypeDetailsDialogRef.value.openDialog(state.selectedDicTypeItem, state.tableData.dicDetailsList, row);
  }
};

// 删除右侧子项
const onDelDicDetails = (row: any) => {
  useDicApi()
    .deleteDictionaryDetail({ id: row.id })
    .then((res: any) => {
      if (res.code === 200) {
        ElMessage.success(res.msg || '删除成功');
        selectDicTypeItem(state.selectedDicTypeItem);
      }
    });
};

// 当新增字典项目提交后
const onDicTypeSubmit = async (data: any) => {
  console.log(data);
  getDicTypeListByName();
};

// 当新增字典子项提交后
const onDicTypeDetailsSubmit = async (data: any) => {
  console.log(data);
  selectDicTypeItem(state.selectedDicTypeItem);
};

// 选中左侧字典项
const selectDicTypeItem = async (item: any) => {
  state.tableData.dicDetailsList = [];
  state.selectedDicTypeItem = item; // 当前选中项
  await useDicApi()
    .queryDicInfoAllByTypeId({ typeId: item.id })
    .then((res: any) => {
      state.tableData.dicDetailsList = res.data.list || [];
    });
};

// const jsonToTree = (inputArr:any[]) => {
// 	// 使用map转存，增加查找效率
// 	const map = new Map();
// 	inputArr.forEach((item) => {
//     map.set(item.id, item);
// 	});

// 	// 将子元素依次放入父元素中
// 	let outputArr:any[] = [];
// 	inputArr.forEach((item) => {
// 		const parent = map.get(item.parentId);
// 		if (parent) {
// 			(parent.children || (parent.children = [])).push(item);
// 		} else {
// 			outputArr.push(item);
// 		}
// 	});
//   return outputArr;
// }
</script>

<style scoped lang="scss">
.my-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  overflow: hidden;

  .group-left {
    width: 20%;
    height: 100%;
    padding: 10px;

    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 5px;
      padding: 10px;
      border-bottom: 1px solid #30539b;

      .title {
        font-size: 18px;
        color: #d7e4ff;
      }

      .btn1 {
        padding: 5px 10px;
        font-size: 16px;
      }
    }

    .list-box {
      padding: 10px;

      ul li:hover {
        background: linear-gradient(88deg, #499afd 0%, #0e45b6 100%) !important;
        color: #fff;
        opacity: 0.6;
      }

      ul li.item {
        display: flex;
        align-items: center;
        width: 100%;
        list-style: none;
        box-sizing: border-box;
        padding: 10px 35px 10px 10px;
        cursor: pointer;
        font-size: 14px;
        margin-bottom: 10px;
        border-radius: 3px;
        color: #d7e4ff;
        position: relative;
        background-color: #193c86;
      }

      ul li.isActive {
        background: linear-gradient(88deg, #499afd 0%, #0e45b6 100%) !important;
        color: #fff;
      }
    }
  }

  .group-right {
    width: 80%;
    height: 100%;
    display: flex;
    flex-direction: column;
    margin-left: 10px;

    .box-details {
      flex: 1;
      padding: 10px 15px;
      position: relative;

      .box-title {
        text-align: center;
        margin-bottom: 20px;
        color: #d7e4ff;
        font-size: 24px;
      }

      .box-search {
        position: absolute;
        top: 10px;
        left: 10px;
      }
    }
  }
}
</style>
